package org.jeecg.config.paramHandler;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sjh
 * @Description
 * @create 2022/11/28 14:07
 */
public class AutoParam extends JSONObject {

    public AutoParam(Map<String, Object> map) {
        if (map == null) map = new HashMap<>();
        this.putAll(map);
    }

    public static <E> AutoParam of(E entity) {
        if (entity == null) return new AutoParam(new HashMap<>());
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(entity).toString());
        return new AutoParam(jsonObject.getInnerMap());
    }

    public void checkParams(String... paramNames) {
        for (String paramName : paramNames) {
            if (!containsKey(paramName)) throw new RuntimeException("缺少" + paramName + "参数");
        }
    }

    public void checkParamsNotBlank(String... paramNames) {
        for (String paramName : paramNames) {
            if (!containsKey(paramName)) throw new RuntimeException("缺少" + paramName + "参数");
            if (StringUtils.isEmpty(getString(paramName))) throw new RuntimeException("参数" + paramName + "不能为空");
        }
    }

    public <E> E getEntity(String key, Class<E> classType) {
        try {
            return getJSONObject(key).toJavaObject(classType);
        } catch (Throwable e) {
            throw new RuntimeException("参数" + key + "转换" + classType.getSimpleName() + "类型失败！");
        }
    }

    public <L> List<L> getList(String key, Class<L> classType) {
        try {
            return getJSONArray(key).toJavaList(classType);
        } catch (Throwable e) {
            throw new RuntimeException("参数" + key + "转换List<" + classType.getSimpleName() + ">类型失败！");
        }
    }

}
